﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace WeiXinService.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public abstract class WeiXinBaseController : Controller
    {
        /// <summary>
        /// <![CDATA[清除xml头部声明]]>
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        protected virtual string ClearXmlHeader(string input)
        {
            return Regex.Replace(input, @"<\?xml([^>]+)\?>", string.Empty, RegexOptions.IgnoreCase);//过滤xml声明
        }

        /// <summary>
        /// <![CDATA[序列号消息]]>
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        protected virtual string Serialize(WeiXin.Sdk.Domain.Messages.MessageBase message)
        {
            using (StringWriter writer = new StringWriter())
            {
                WeiXin.Sdk.Common.Serialization.XmlSerializer xmlSerializer = new WeiXin.Sdk.Common.Serialization.XmlSerializer(message.GetType());
                xmlSerializer.Serialize(writer, message);
                string strResponseContent = writer.ToString();
                strResponseContent = ClearXmlHeader(strResponseContent);//过滤xml声明
                return strResponseContent;
            }
        }
    }
}